Filename | (eval 167)[/usr/share/perl5/JSON.pm:268] |
Statements | Executed 0 statements in 0s |
Eval Invoked At | /usr/share/perl5/JSON.pm line 268 |
Calls | P | F | Exclusive Time |
Inclusive Time |
Subroutine |
---|---|---|---|---|---|
1 | 1 | 1 | 45µs | 45µs | init | JSON::Backend::XS::
1 | 1 | 1 | 27µs | 82µs | BEGIN@9 | JSON::Backend::XS::
1 | 1 | 1 | 22µs | 34µs | BEGIN@99 | JSON::Backend::XS::Supportable::
1 | 1 | 1 | 11µs | 26µs | BEGIN@18 | JSON::Backend::XS::
1 | 1 | 1 | 11µs | 29µs | BEGIN@11 | JSON::Backend::XS::
1 | 1 | 1 | 8µs | 20µs | BEGIN@29 | JSON::Backend::XS::
1 | 1 | 1 | 8µs | 14µs | BEGIN@42 | JSON::Backend::XS::
0 | 0 | 0 | 0s | 0s | __ANON__[:110] | JSON::Backend::XS::Supportable::
0 | 0 | 0 | 0s | 0s | __ANON__[:114] | JSON::Backend::XS::Supportable::
0 | 0 | 0 | 0s | 0s | _decode | JSON::Backend::XS::Supportable::
0 | 0 | 0 | 0s | 0s | _encode | JSON::Backend::XS::Supportable::
0 | 0 | 0 | 0s | 0s | _incr_parse | JSON::Backend::XS::Supportable::
0 | 0 | 0 | 0s | 0s | _make_unsupported_method | JSON::Backend::XS::Supportable::
0 | 0 | 0 | 0s | 0s | _set_for_pp | JSON::Backend::XS::Supportable::
0 | 0 | 0 | 0s | 0s | decode_prefix | JSON::Backend::XS::Supportable::
0 | 0 | 0 | 0s | 0s | get_indent_length | JSON::Backend::XS::Supportable::
0 | 0 | 0 | 0s | 0s | indent_length | JSON::Backend::XS::Supportable::
0 | 0 | 0 | 0s | 0s | __ANON__[:32] | JSON::Backend::XS::
0 | 0 | 0 | 0s | 0s | __ANON__[:33] | JSON::Backend::XS::
0 | 0 | 0 | 0s | 0s | __ANON__[:63] | JSON::Backend::XS::
0 | 0 | 0 | 0s | 0s | support_by_pp | JSON::Backend::XS::
Line | State ments |
Time on line |
Calls | Time in subs |
Code |
---|---|---|---|---|---|
1 | |||||
2 | |||||
3 | # | ||||
4 | # Helper classes for Backend Module (XS) | ||||
5 | # | ||||
6 | |||||
7 | package JSON::Backend::XS; | ||||
8 | |||||
9 | 2 | 138µs | # spent 82µs (27+55) within JSON::Backend::XS::BEGIN@9 which was called:
# once (27µs+55µs) by JSON::_load_xs at line 9 # spent 82µs making 1 call to JSON::Backend::XS::BEGIN@9
# spent 55µs making 1 call to constant::import | ||
10 | |||||
11 | 1 | 18µs | # spent 29µs (11+18) within JSON::Backend::XS::BEGIN@11 which was called:
# once (11µs+18µs) by JSON::_load_xs at line 16 # spent 18µs making 1 call to constant::import | ||
12 | ESCAPE_SLASH => 0x00000010, | ||||
13 | ALLOW_BIGNUM => 0x00000020, | ||||
14 | AS_NONBLESSED => 0x00000040, | ||||
15 | EXPANDED => 0x10000000, # for developer's | ||||
16 | 1 | 29µs | }; # spent 29µs making 1 call to JSON::Backend::XS::BEGIN@11 | ||
17 | |||||
18 | 1 | 15µs | # spent 26µs (11+15) within JSON::Backend::XS::BEGIN@18 which was called:
# once (11µs+15µs) by JSON::_load_xs at line 24 # spent 15µs making 1 call to constant::import | ||
19 | LOOSE => 0x00000001, | ||||
20 | ALLOW_BIGNUM => 0x00000002, | ||||
21 | ALLOW_BAREKEY => 0x00000004, | ||||
22 | ALLOW_SINGLEQUOTE => 0x00000008, | ||||
23 | EXPANDED => 0x20000000, # for developer's | ||||
24 | 1 | 26µs | }; # spent 26µs making 1 call to JSON::Backend::XS::BEGIN@18 | ||
25 | |||||
26 | |||||
27 | # spent 45µs within JSON::Backend::XS::init which was called:
# once (45µs+0s) by JSON::_load_xs at line 269 of JSON.pm | ||||
28 | local $^W; | ||||
29 | 2 | 32µs | # spent 20µs (8+12) within JSON::Backend::XS::BEGIN@29 which was called:
# once (8µs+12µs) by JSON::_load_xs at line 29 # spent 20µs making 1 call to JSON::Backend::XS::BEGIN@29
# spent 12µs making 1 call to strict::unimport | ||
30 | *{"JSON::decode_json"} = \&{"JSON::XS::decode_json"}; | ||||
31 | *{"JSON::encode_json"} = \&{"JSON::XS::encode_json"}; | ||||
32 | *{"JSON::XS::is_xs"} = sub { 1 }; | ||||
33 | *{"JSON::XS::is_pp"} = sub { 0 }; | ||||
34 | return 1; | ||||
35 | } | ||||
36 | |||||
37 | |||||
38 | sub support_by_pp { | ||||
39 | my ($class, @methods) = @_; | ||||
40 | |||||
41 | local $^W; | ||||
42 | 2 | 19µs | # spent 14µs (8+5) within JSON::Backend::XS::BEGIN@42 which was called:
# once (8µs+5µs) by JSON::_load_xs at line 42 # spent 14µs making 1 call to JSON::Backend::XS::BEGIN@42
# spent 5µs making 1 call to strict::unimport | ||
43 | |||||
44 | my $JSON_XS_encode_orignal = \&JSON::XS::encode; | ||||
45 | my $JSON_XS_decode_orignal = \&JSON::XS::decode; | ||||
46 | my $JSON_XS_incr_parse_orignal = \&JSON::XS::incr_parse; | ||||
47 | |||||
48 | *JSON::XS::decode = \&JSON::Backend::XS::Supportable::_decode; | ||||
49 | *JSON::XS::encode = \&JSON::Backend::XS::Supportable::_encode; | ||||
50 | *JSON::XS::incr_parse = \&JSON::Backend::XS::Supportable::_incr_parse; | ||||
51 | |||||
52 | *{JSON::XS::_original_decode} = $JSON_XS_decode_orignal; | ||||
53 | *{JSON::XS::_original_encode} = $JSON_XS_encode_orignal; | ||||
54 | *{JSON::XS::_original_incr_parse} = $JSON_XS_incr_parse_orignal; | ||||
55 | |||||
56 | push @JSON::Backend::XS::Supportable::ISA, 'JSON'; | ||||
57 | |||||
58 | my $pkg = 'JSON::Backend::XS::Supportable'; | ||||
59 | |||||
60 | *{JSON::new} = sub { | ||||
61 | my $proto = JSON::XS->new; $$proto = 0; | ||||
62 | bless $proto, $pkg; | ||||
63 | }; | ||||
64 | |||||
65 | |||||
66 | for my $method (@methods) { | ||||
67 | my $flag = uc($method); | ||||
68 | my $type |= (UNSUPPORTED_ENCODE_FLAG->{$flag} || 0); | ||||
69 | $type |= (UNSUPPORTED_DECODE_FLAG->{$flag} || 0); | ||||
70 | |||||
71 | next unless($type); | ||||
72 | |||||
73 | $pkg->_make_unsupported_method($method => $type); | ||||
74 | } | ||||
75 | |||||
76 | push @{"JSON::XS::Boolean::ISA"}, qw(JSON::PP::Boolean); | ||||
77 | push @{"JSON::PP::Boolean::ISA"}, qw(JSON::Boolean); | ||||
78 | |||||
79 | $JSON::DEBUG and Carp::carp("set -support_by_pp mode."); | ||||
80 | |||||
81 | return 1; | ||||
82 | } | ||||
83 | |||||
- - | |||||
87 | # | ||||
88 | # Helper classes for XS | ||||
89 | # | ||||
90 | |||||
91 | package JSON::Backend::XS::Supportable; | ||||
92 | |||||
93 | $Carp::Internal{'JSON::Backend::XS::Supportable'} = 1; | ||||
94 | |||||
95 | sub _make_unsupported_method { | ||||
96 | my ($pkg, $method, $type) = @_; | ||||
97 | |||||
98 | local $^W; | ||||
99 | 2 | 46µs | # spent 34µs (22+12) within JSON::Backend::XS::Supportable::BEGIN@99 which was called:
# once (22µs+12µs) by JSON::_load_xs at line 99 # spent 34µs making 1 call to JSON::Backend::XS::Supportable::BEGIN@99
# spent 12µs making 1 call to strict::unimport | ||
100 | |||||
101 | *{"$pkg\::$method"} = sub { | ||||
102 | local $^W; | ||||
103 | if (defined $_[1] ? $_[1] : 1) { | ||||
104 | ${$_[0]} |= $type; | ||||
105 | } | ||||
106 | else { | ||||
107 | ${$_[0]} &= ~$type; | ||||
108 | } | ||||
109 | $_[0]; | ||||
110 | }; | ||||
111 | |||||
112 | *{"$pkg\::get_$method"} = sub { | ||||
113 | ${$_[0]} & $type ? 1 : ''; | ||||
114 | }; | ||||
115 | |||||
116 | } | ||||
117 | |||||
118 | |||||
119 | sub _set_for_pp { | ||||
120 | JSON::_load_pp( $_INSTALL_ONLY ); | ||||
121 | |||||
122 | my $type = shift; | ||||
123 | my $pp = JSON::PP->new; | ||||
124 | my $prop = $_[0]->property; | ||||
125 | |||||
126 | for my $name (keys %$prop) { | ||||
127 | $pp->$name( $prop->{$name} ? $prop->{$name} : 0 ); | ||||
128 | } | ||||
129 | |||||
130 | my $unsupported = $type eq 'encode' ? JSON::Backend::XS::UNSUPPORTED_ENCODE_FLAG | ||||
131 | : JSON::Backend::XS::UNSUPPORTED_DECODE_FLAG; | ||||
132 | my $flags = ${$_[0]} || 0; | ||||
133 | |||||
134 | for my $name (keys %$unsupported) { | ||||
135 | next if ($name eq 'EXPANDED'); # for developer's | ||||
136 | my $enable = ($flags & $unsupported->{$name}) ? 1 : 0; | ||||
137 | my $method = lc $name; | ||||
138 | $pp->$method($enable); | ||||
139 | } | ||||
140 | |||||
141 | $pp->indent_length( $_[0]->get_indent_length ); | ||||
142 | |||||
143 | return $pp; | ||||
144 | } | ||||
145 | |||||
146 | sub _encode { # using with PP encode | ||||
147 | if (${$_[0]}) { | ||||
148 | _set_for_pp('encode' => @_)->encode($_[1]); | ||||
149 | } | ||||
150 | else { | ||||
151 | $_[0]->_original_encode( $_[1] ); | ||||
152 | } | ||||
153 | } | ||||
154 | |||||
155 | |||||
156 | sub _decode { # if unsupported-flag is set, use PP | ||||
157 | if (${$_[0]}) { | ||||
158 | _set_for_pp('decode' => @_)->decode($_[1]); | ||||
159 | } | ||||
160 | else { | ||||
161 | $_[0]->_original_decode( $_[1] ); | ||||
162 | } | ||||
163 | } | ||||
164 | |||||
165 | |||||
166 | sub decode_prefix { # if unsupported-flag is set, use PP | ||||
167 | _set_for_pp('decode' => @_)->decode_prefix($_[1]); | ||||
168 | } | ||||
169 | |||||
170 | |||||
171 | sub _incr_parse { | ||||
172 | if (${$_[0]}) { | ||||
173 | _set_for_pp('decode' => @_)->incr_parse($_[1]); | ||||
174 | } | ||||
175 | else { | ||||
176 | $_[0]->_original_incr_parse( $_[1] ); | ||||
177 | } | ||||
178 | } | ||||
179 | |||||
180 | |||||
181 | sub get_indent_length { | ||||
182 | ${$_[0]} << 4 >> 16; | ||||
183 | } | ||||
184 | |||||
185 | |||||
186 | sub indent_length { | ||||
187 | my $length = $_[1]; | ||||
188 | |||||
189 | if (!defined $length or $length > 15 or $length < 0) { | ||||
190 | Carp::carp "The acceptable range of indent_length() is 0 to 15."; | ||||
191 | } | ||||
192 | else { | ||||
193 | local $^W; | ||||
194 | $length <<= 12; | ||||
195 | ${$_[0]} &= ~ JSON::Backend::XS::INDENT_LENGTH_FLAG; | ||||
196 | ${$_[0]} |= $length; | ||||
197 | *JSON::XS::encode = \&JSON::Backend::XS::Supportable::_encode; | ||||
198 | } | ||||
199 | |||||
200 | $_[0]; | ||||
201 | } | ||||
202 | |||||
203 | |||||
204 | 1; | ||||
205 | __END__ | ||||
206 | |||||
207 | =head1 NAME | ||||
208 | |||||
209 | JSON - JSON (JavaScript Object Notation) encoder/decoder | ||||
210 | |||||
211 | =head1 SYNOPSIS | ||||
212 | |||||
213 | use JSON; # imports encode_json, decode_json, to_json and from_json. | ||||
214 | |||||
215 | # simple and fast interfaces (expect/generate UTF-8) | ||||
216 | |||||
217 | $utf8_encoded_json_text = encode_json $perl_hash_or_arrayref; | ||||
218 | $perl_hash_or_arrayref = decode_json $utf8_encoded_json_text; | ||||
219 | |||||
220 | # OO-interface | ||||
221 | |||||
222 | $json = JSON->new->allow_nonref; | ||||
223 | |||||
224 | $json_text = $json->encode( $perl_scalar ); | ||||
225 | $perl_scalar = $json->decode( $json_text ); | ||||
226 | |||||
227 | $pretty_printed = $json->pretty->encode( $perl_scalar ); # pretty-printing | ||||
228 | |||||
229 | # If you want to use PP only support features, call with '-support_by_pp' | ||||
230 | # When XS unsupported feature is enable, using PP (de|en)code instead of XS ones. | ||||
231 | |||||
232 | use JSON -support_by_pp; | ||||
233 | |||||
234 | # option-acceptable interfaces (expect/generate UNICODE by default) | ||||
235 | |||||
236 | $json_text = to_json( $perl_scalar, { ascii => 1, pretty => 1 } ); | ||||
237 | $perl_scalar = from_json( $json_text, { utf8 => 1 } ); | ||||
238 | |||||
239 | # Between (en|de)code_json and (to|from)_json, if you want to write | ||||
240 | # a code which communicates to an outer world (encoded in UTF-8), | ||||
241 | # recommend to use (en|de)code_json. | ||||
242 | |||||
243 | =head1 VERSION | ||||
244 | |||||
245 | 2.59 | ||||
246 | |||||
247 | This version is compatible with JSON::XS B<2.34> and later. | ||||
248 | |||||
249 | |||||
250 | =head1 NOTE | ||||
251 | |||||
252 | JSON::PP was earlier included in the C<JSON> distribution, but | ||||
253 | has since Perl 5.14 been a core module. For this reason, | ||||
254 | L<JSON::PP> was removed from the JSON distribution and can now | ||||
255 | be found also in the Perl5 repository at | ||||
256 | |||||
257 | =over | ||||
258 | |||||
259 | =item * L<http://perl5.git.perl.org/perl.git> | ||||
260 | |||||
261 | =back | ||||
262 | |||||
263 | (The newest JSON::PP version still exists in CPAN.) | ||||
264 | |||||
265 | Instead, the C<JSON> distribution will include JSON::backportPP | ||||
266 | for backwards computability. JSON.pm should thus work as it did | ||||
267 | before. | ||||
268 | |||||
269 | =head1 DESCRIPTION | ||||
270 | |||||
271 | ************************** CAUTION ******************************** | ||||
272 | * This is 'JSON module version 2' and there are many differences * | ||||
273 | * to version 1.xx * | ||||
274 | * Please check your applications using old version. * | ||||
275 | * See to 'INCOMPATIBLE CHANGES TO OLD VERSION' * | ||||
276 | ******************************************************************* | ||||
277 | |||||
278 | JSON (JavaScript Object Notation) is a simple data format. | ||||
279 | See to L<http://www.json.org/> and C<RFC4627>(L<http://www.ietf.org/rfc/rfc4627.txt>). | ||||
280 | |||||
281 | This module converts Perl data structures to JSON and vice versa using either | ||||
282 | L<JSON::XS> or L<JSON::PP>. | ||||
283 | |||||
284 | JSON::XS is the fastest and most proper JSON module on CPAN which must be | ||||
285 | compiled and installed in your environment. | ||||
286 | JSON::PP is a pure-Perl module which is bundled in this distribution and | ||||
287 | has a strong compatibility to JSON::XS. | ||||
288 | |||||
289 | This module try to use JSON::XS by default and fail to it, use JSON::PP instead. | ||||
290 | So its features completely depend on JSON::XS or JSON::PP. | ||||
291 | |||||
292 | See to L<BACKEND MODULE DECISION>. | ||||
293 | |||||
294 | To distinguish the module name 'JSON' and the format type JSON, | ||||
295 | the former is quoted by CE<lt>E<gt> (its results vary with your using media), | ||||
296 | and the latter is left just as it is. | ||||
297 | |||||
298 | Module name : C<JSON> | ||||
299 | |||||
300 | Format type : JSON | ||||
301 | |||||
302 | =head2 FEATURES | ||||
303 | |||||
304 | =over | ||||
305 | |||||
306 | =item * correct unicode handling | ||||
307 | |||||
308 | This module (i.e. backend modules) knows how to handle Unicode, documents | ||||
309 | how and when it does so, and even documents what "correct" means. | ||||
310 | |||||
311 | Even though there are limitations, this feature is available since Perl version 5.6. | ||||
312 | |||||
313 | JSON::XS requires Perl 5.8.2 (but works correctly in 5.8.8 or later), so in older versions | ||||
314 | C<JSON> should call JSON::PP as the backend which can be used since Perl 5.005. | ||||
315 | |||||
316 | With Perl 5.8.x JSON::PP works, but from 5.8.0 to 5.8.2, because of a Perl side problem, | ||||
317 | JSON::PP works slower in the versions. And in 5.005, the Unicode handling is not available. | ||||
318 | See to L<JSON::PP/UNICODE HANDLING ON PERLS> for more information. | ||||
319 | |||||
320 | See also to L<JSON::XS/A FEW NOTES ON UNICODE AND PERL> | ||||
321 | and L<JSON::XS/ENCODING/CODESET_FLAG_NOTES>. | ||||
322 | |||||
323 | |||||
324 | =item * round-trip integrity | ||||
325 | |||||
326 | When you serialise a perl data structure using only data types supported | ||||
327 | by JSON and Perl, the deserialised data structure is identical on the Perl | ||||
328 | level. (e.g. the string "2.0" doesn't suddenly become "2" just because | ||||
329 | it looks like a number). There I<are> minor exceptions to this, read the | ||||
330 | L</MAPPING> section below to learn about those. | ||||
331 | |||||
332 | |||||
333 | =item * strict checking of JSON correctness | ||||
334 | |||||
335 | There is no guessing, no generating of illegal JSON texts by default, | ||||
336 | and only JSON is accepted as input by default (the latter is a security | ||||
337 | feature). | ||||
338 | |||||
339 | See to L<JSON::XS/FEATURES> and L<JSON::PP/FEATURES>. | ||||
340 | |||||
341 | =item * fast | ||||
342 | |||||
343 | This module returns a JSON::XS object itself if available. | ||||
344 | Compared to other JSON modules and other serialisers such as Storable, | ||||
345 | JSON::XS usually compares favorably in terms of speed, too. | ||||
346 | |||||
347 | If not available, C<JSON> returns a JSON::PP object instead of JSON::XS and | ||||
348 | it is very slow as pure-Perl. | ||||
349 | |||||
350 | =item * simple to use | ||||
351 | |||||
352 | This module has both a simple functional interface as well as an | ||||
353 | object oriented interface interface. | ||||
354 | |||||
355 | =item * reasonably versatile output formats | ||||
356 | |||||
357 | You can choose between the most compact guaranteed-single-line format possible | ||||
358 | (nice for simple line-based protocols), a pure-ASCII format (for when your transport | ||||
359 | is not 8-bit clean, still supports the whole Unicode range), or a pretty-printed | ||||
360 | format (for when you want to read that stuff). Or you can combine those features | ||||
361 | in whatever way you like. | ||||
362 | |||||
363 | =back | ||||
364 | |||||
365 | =head1 FUNCTIONAL INTERFACE | ||||
366 | |||||
367 | Some documents are copied and modified from L<JSON::XS/FUNCTIONAL INTERFACE>. | ||||
368 | C<to_json> and C<from_json> are additional functions. | ||||
369 | |||||
370 | =head2 encode_json | ||||
371 | |||||
372 | $json_text = encode_json $perl_scalar | ||||
373 | |||||
374 | Converts the given Perl data structure to a UTF-8 encoded, binary string. | ||||
375 | |||||
376 | This function call is functionally identical to: | ||||
377 | |||||
378 | $json_text = JSON->new->utf8->encode($perl_scalar) | ||||
379 | |||||
380 | =head2 decode_json | ||||
381 | |||||
382 | $perl_scalar = decode_json $json_text | ||||
383 | |||||
384 | The opposite of C<encode_json>: expects an UTF-8 (binary) string and tries | ||||
385 | to parse that as an UTF-8 encoded JSON text, returning the resulting | ||||
386 | reference. | ||||
387 | |||||
388 | This function call is functionally identical to: | ||||
389 | |||||
390 | $perl_scalar = JSON->new->utf8->decode($json_text) | ||||
391 | |||||
392 | |||||
393 | =head2 to_json | ||||
394 | |||||
395 | $json_text = to_json($perl_scalar) | ||||
396 | |||||
397 | Converts the given Perl data structure to a json string. | ||||
398 | |||||
399 | This function call is functionally identical to: | ||||
400 | |||||
401 | $json_text = JSON->new->encode($perl_scalar) | ||||
402 | |||||
403 | Takes a hash reference as the second. | ||||
404 | |||||
405 | $json_text = to_json($perl_scalar, $flag_hashref) | ||||
406 | |||||
407 | So, | ||||
408 | |||||
409 | $json_text = to_json($perl_scalar, {utf8 => 1, pretty => 1}) | ||||
410 | |||||
411 | equivalent to: | ||||
412 | |||||
413 | $json_text = JSON->new->utf8(1)->pretty(1)->encode($perl_scalar) | ||||
414 | |||||
415 | If you want to write a modern perl code which communicates to outer world, | ||||
416 | you should use C<encode_json> (supposed that JSON data are encoded in UTF-8). | ||||
417 | |||||
418 | =head2 from_json | ||||
419 | |||||
420 | $perl_scalar = from_json($json_text) | ||||
421 | |||||
422 | The opposite of C<to_json>: expects a json string and tries | ||||
423 | to parse it, returning the resulting reference. | ||||
424 | |||||
425 | This function call is functionally identical to: | ||||
426 | |||||
427 | $perl_scalar = JSON->decode($json_text) | ||||
428 | |||||
429 | Takes a hash reference as the second. | ||||
430 | |||||
431 | $perl_scalar = from_json($json_text, $flag_hashref) | ||||
432 | |||||
433 | So, | ||||
434 | |||||
435 | $perl_scalar = from_json($json_text, {utf8 => 1}) | ||||
436 | |||||
437 | equivalent to: | ||||
438 | |||||
439 | $perl_scalar = JSON->new->utf8(1)->decode($json_text) | ||||
440 | |||||
441 | If you want to write a modern perl code which communicates to outer world, | ||||
442 | you should use C<decode_json> (supposed that JSON data are encoded in UTF-8). | ||||
443 | |||||
444 | =head2 JSON::is_bool | ||||
445 | |||||
446 | $is_boolean = JSON::is_bool($scalar) | ||||
447 | |||||
448 | Returns true if the passed scalar represents either JSON::true or | ||||
449 | JSON::false, two constants that act like C<1> and C<0> respectively | ||||
450 | and are also used to represent JSON C<true> and C<false> in Perl strings. | ||||
451 | |||||
452 | =head2 JSON::true | ||||
453 | |||||
454 | Returns JSON true value which is blessed object. | ||||
455 | It C<isa> JSON::Boolean object. | ||||
456 | |||||
457 | =head2 JSON::false | ||||
458 | |||||
459 | Returns JSON false value which is blessed object. | ||||
460 | It C<isa> JSON::Boolean object. | ||||
461 | |||||
462 | =head2 JSON::null | ||||
463 | |||||
464 | Returns C<undef>. | ||||
465 | |||||
466 | See L<MAPPING>, below, for more information on how JSON values are mapped to | ||||
467 | Perl. | ||||
468 | |||||
469 | =head1 HOW DO I DECODE A DATA FROM OUTER AND ENCODE TO OUTER | ||||
470 | |||||
471 | This section supposes that your perl version is 5.8 or later. | ||||
472 | |||||
473 | If you know a JSON text from an outer world - a network, a file content, and so on, | ||||
474 | is encoded in UTF-8, you should use C<decode_json> or C<JSON> module object | ||||
475 | with C<utf8> enable. And the decoded result will contain UNICODE characters. | ||||
476 | |||||
477 | # from network | ||||
478 | my $json = JSON->new->utf8; | ||||
479 | my $json_text = CGI->new->param( 'json_data' ); | ||||
480 | my $perl_scalar = $json->decode( $json_text ); | ||||
481 | |||||
482 | # from file content | ||||
483 | local $/; | ||||
484 | open( my $fh, '<', 'json.data' ); | ||||
485 | $json_text = <$fh>; | ||||
486 | $perl_scalar = decode_json( $json_text ); | ||||
487 | |||||
488 | If an outer data is not encoded in UTF-8, firstly you should C<decode> it. | ||||
489 | |||||
490 | use Encode; | ||||
491 | local $/; | ||||
492 | open( my $fh, '<', 'json.data' ); | ||||
493 | my $encoding = 'cp932'; | ||||
494 | my $unicode_json_text = decode( $encoding, <$fh> ); # UNICODE | ||||
495 | |||||
496 | # or you can write the below code. | ||||
497 | # | ||||
498 | # open( my $fh, "<:encoding($encoding)", 'json.data' ); | ||||
499 | # $unicode_json_text = <$fh>; | ||||
500 | |||||
501 | In this case, C<$unicode_json_text> is of course UNICODE string. | ||||
502 | So you B<cannot> use C<decode_json> nor C<JSON> module object with C<utf8> enable. | ||||
503 | Instead of them, you use C<JSON> module object with C<utf8> disable or C<from_json>. | ||||
504 | |||||
505 | $perl_scalar = $json->utf8(0)->decode( $unicode_json_text ); | ||||
506 | # or | ||||
507 | $perl_scalar = from_json( $unicode_json_text ); | ||||
508 | |||||
509 | Or C<encode 'utf8'> and C<decode_json>: | ||||
510 | |||||
511 | $perl_scalar = decode_json( encode( 'utf8', $unicode_json_text ) ); | ||||
512 | # this way is not efficient. | ||||
513 | |||||
514 | And now, you want to convert your C<$perl_scalar> into JSON data and | ||||
515 | send it to an outer world - a network or a file content, and so on. | ||||
516 | |||||
517 | Your data usually contains UNICODE strings and you want the converted data to be encoded | ||||
518 | in UTF-8, you should use C<encode_json> or C<JSON> module object with C<utf8> enable. | ||||
519 | |||||
520 | print encode_json( $perl_scalar ); # to a network? file? or display? | ||||
521 | # or | ||||
522 | print $json->utf8->encode( $perl_scalar ); | ||||
523 | |||||
524 | If C<$perl_scalar> does not contain UNICODE but C<$encoding>-encoded strings | ||||
525 | for some reason, then its characters are regarded as B<latin1> for perl | ||||
526 | (because it does not concern with your $encoding). | ||||
527 | You B<cannot> use C<encode_json> nor C<JSON> module object with C<utf8> enable. | ||||
528 | Instead of them, you use C<JSON> module object with C<utf8> disable or C<to_json>. | ||||
529 | Note that the resulted text is a UNICODE string but no problem to print it. | ||||
530 | |||||
531 | # $perl_scalar contains $encoding encoded string values | ||||
532 | $unicode_json_text = $json->utf8(0)->encode( $perl_scalar ); | ||||
533 | # or | ||||
534 | $unicode_json_text = to_json( $perl_scalar ); | ||||
535 | # $unicode_json_text consists of characters less than 0x100 | ||||
536 | print $unicode_json_text; | ||||
537 | |||||
538 | Or C<decode $encoding> all string values and C<encode_json>: | ||||
539 | |||||
540 | $perl_scalar->{ foo } = decode( $encoding, $perl_scalar->{ foo } ); | ||||
541 | # ... do it to each string values, then encode_json | ||||
542 | $json_text = encode_json( $perl_scalar ); | ||||
543 | |||||
544 | This method is a proper way but probably not efficient. | ||||
545 | |||||
546 | See to L<Encode>, L<perluniintro>. | ||||
547 | |||||
548 | |||||
549 | =head1 COMMON OBJECT-ORIENTED INTERFACE | ||||
550 | |||||
551 | =head2 new | ||||
552 | |||||
553 | $json = JSON->new | ||||
554 | |||||
555 | Returns a new C<JSON> object inherited from either JSON::XS or JSON::PP | ||||
556 | that can be used to de/encode JSON strings. | ||||
557 | |||||
558 | All boolean flags described below are by default I<disabled>. | ||||
559 | |||||
560 | The mutators for flags all return the JSON object again and thus calls can | ||||
561 | be chained: | ||||
562 | |||||
563 | my $json = JSON->new->utf8->space_after->encode({a => [1,2]}) | ||||
564 | => {"a": [1, 2]} | ||||
565 | |||||
566 | =head2 ascii | ||||
567 | |||||
568 | $json = $json->ascii([$enable]) | ||||
569 | |||||
570 | $enabled = $json->get_ascii | ||||
571 | |||||
572 | If $enable is true (or missing), then the encode method will not generate characters outside | ||||
573 | the code range 0..127. Any Unicode characters outside that range will be escaped using either | ||||
574 | a single \uXXXX or a double \uHHHH\uLLLLL escape sequence, as per RFC4627. | ||||
575 | |||||
576 | If $enable is false, then the encode method will not escape Unicode characters unless | ||||
577 | required by the JSON syntax or other flags. This results in a faster and more compact format. | ||||
578 | |||||
579 | This feature depends on the used Perl version and environment. | ||||
580 | |||||
581 | See to L<JSON::PP/UNICODE HANDLING ON PERLS> if the backend is PP. | ||||
582 | |||||
583 | JSON->new->ascii(1)->encode([chr 0x10401]) | ||||
584 | => ["\ud801\udc01"] | ||||
585 | |||||
586 | =head2 latin1 | ||||
587 | |||||
588 | $json = $json->latin1([$enable]) | ||||
589 | |||||
590 | $enabled = $json->get_latin1 | ||||
591 | |||||
592 | If $enable is true (or missing), then the encode method will encode the resulting JSON | ||||
593 | text as latin1 (or iso-8859-1), escaping any characters outside the code range 0..255. | ||||
594 | |||||
595 | If $enable is false, then the encode method will not escape Unicode characters | ||||
596 | unless required by the JSON syntax or other flags. | ||||
597 | |||||
598 | JSON->new->latin1->encode (["\x{89}\x{abc}"] | ||||
599 | => ["\x{89}\\u0abc"] # (perl syntax, U+abc escaped, U+89 not) | ||||
600 | |||||
601 | =head2 utf8 | ||||
602 | |||||
603 | $json = $json->utf8([$enable]) | ||||
604 | |||||
605 | $enabled = $json->get_utf8 | ||||
606 | |||||
607 | If $enable is true (or missing), then the encode method will encode the JSON result | ||||
608 | into UTF-8, as required by many protocols, while the decode method expects to be handled | ||||
609 | an UTF-8-encoded string. Please note that UTF-8-encoded strings do not contain any | ||||
610 | characters outside the range 0..255, they are thus useful for bytewise/binary I/O. | ||||
611 | |||||
612 | In future versions, enabling this option might enable autodetection of the UTF-16 and UTF-32 | ||||
613 | encoding families, as described in RFC4627. | ||||
614 | |||||
615 | If $enable is false, then the encode method will return the JSON string as a (non-encoded) | ||||
616 | Unicode string, while decode expects thus a Unicode string. Any decoding or encoding | ||||
617 | (e.g. to UTF-8 or UTF-16) needs to be done yourself, e.g. using the Encode module. | ||||
618 | |||||
619 | |||||
620 | Example, output UTF-16BE-encoded JSON: | ||||
621 | |||||
622 | use Encode; | ||||
623 | $jsontext = encode "UTF-16BE", JSON::XS->new->encode ($object); | ||||
624 | |||||
625 | Example, decode UTF-32LE-encoded JSON: | ||||
626 | |||||
627 | use Encode; | ||||
628 | $object = JSON::XS->new->decode (decode "UTF-32LE", $jsontext); | ||||
629 | |||||
630 | See to L<JSON::PP/UNICODE HANDLING ON PERLS> if the backend is PP. | ||||
631 | |||||
632 | |||||
633 | =head2 pretty | ||||
634 | |||||
635 | $json = $json->pretty([$enable]) | ||||
636 | |||||
637 | This enables (or disables) all of the C<indent>, C<space_before> and | ||||
638 | C<space_after> (and in the future possibly more) flags in one call to | ||||
639 | generate the most readable (or most compact) form possible. | ||||
640 | |||||
641 | Equivalent to: | ||||
642 | |||||
643 | $json->indent->space_before->space_after | ||||
644 | |||||
645 | The indent space length is three and JSON::XS cannot change the indent | ||||
646 | space length. | ||||
647 | |||||
648 | =head2 indent | ||||
649 | |||||
650 | $json = $json->indent([$enable]) | ||||
651 | |||||
652 | $enabled = $json->get_indent | ||||
653 | |||||
654 | If C<$enable> is true (or missing), then the C<encode> method will use a multiline | ||||
655 | format as output, putting every array member or object/hash key-value pair | ||||
656 | into its own line, identifying them properly. | ||||
657 | |||||
658 | If C<$enable> is false, no newlines or indenting will be produced, and the | ||||
659 | resulting JSON text is guaranteed not to contain any C<newlines>. | ||||
660 | |||||
661 | This setting has no effect when decoding JSON texts. | ||||
662 | |||||
663 | The indent space length is three. | ||||
664 | With JSON::PP, you can also access C<indent_length> to change indent space length. | ||||
665 | |||||
666 | |||||
667 | =head2 space_before | ||||
668 | |||||
669 | $json = $json->space_before([$enable]) | ||||
670 | |||||
671 | $enabled = $json->get_space_before | ||||
672 | |||||
673 | If C<$enable> is true (or missing), then the C<encode> method will add an extra | ||||
674 | optional space before the C<:> separating keys from values in JSON objects. | ||||
675 | |||||
676 | If C<$enable> is false, then the C<encode> method will not add any extra | ||||
677 | space at those places. | ||||
678 | |||||
679 | This setting has no effect when decoding JSON texts. | ||||
680 | |||||
681 | Example, space_before enabled, space_after and indent disabled: | ||||
682 | |||||
683 | {"key" :"value"} | ||||
684 | |||||
685 | |||||
686 | =head2 space_after | ||||
687 | |||||
688 | $json = $json->space_after([$enable]) | ||||
689 | |||||
690 | $enabled = $json->get_space_after | ||||
691 | |||||
692 | If C<$enable> is true (or missing), then the C<encode> method will add an extra | ||||
693 | optional space after the C<:> separating keys from values in JSON objects | ||||
694 | and extra whitespace after the C<,> separating key-value pairs and array | ||||
695 | members. | ||||
696 | |||||
697 | If C<$enable> is false, then the C<encode> method will not add any extra | ||||
698 | space at those places. | ||||
699 | |||||
700 | This setting has no effect when decoding JSON texts. | ||||
701 | |||||
702 | Example, space_before and indent disabled, space_after enabled: | ||||
703 | |||||
704 | {"key": "value"} | ||||
705 | |||||
706 | |||||
707 | =head2 relaxed | ||||
708 | |||||
709 | $json = $json->relaxed([$enable]) | ||||
710 | |||||
711 | $enabled = $json->get_relaxed | ||||
712 | |||||
713 | If C<$enable> is true (or missing), then C<decode> will accept some | ||||
714 | extensions to normal JSON syntax (see below). C<encode> will not be | ||||
715 | affected in anyway. I<Be aware that this option makes you accept invalid | ||||
716 | JSON texts as if they were valid!>. I suggest only to use this option to | ||||
717 | parse application-specific files written by humans (configuration files, | ||||
718 | resource files etc.) | ||||
719 | |||||
720 | If C<$enable> is false (the default), then C<decode> will only accept | ||||
721 | valid JSON texts. | ||||
722 | |||||
723 | Currently accepted extensions are: | ||||
724 | |||||
725 | =over 4 | ||||
726 | |||||
727 | =item * list items can have an end-comma | ||||
728 | |||||
729 | JSON I<separates> array elements and key-value pairs with commas. This | ||||
730 | can be annoying if you write JSON texts manually and want to be able to | ||||
731 | quickly append elements, so this extension accepts comma at the end of | ||||
732 | such items not just between them: | ||||
733 | |||||
734 | [ | ||||
735 | 1, | ||||
736 | 2, <- this comma not normally allowed | ||||
737 | ] | ||||
738 | { | ||||
739 | "k1": "v1", | ||||
740 | "k2": "v2", <- this comma not normally allowed | ||||
741 | } | ||||
742 | |||||
743 | =item * shell-style '#'-comments | ||||
744 | |||||
745 | Whenever JSON allows whitespace, shell-style comments are additionally | ||||
746 | allowed. They are terminated by the first carriage-return or line-feed | ||||
747 | character, after which more white-space and comments are allowed. | ||||
748 | |||||
749 | [ | ||||
750 | 1, # this comment not allowed in JSON | ||||
751 | # neither this one... | ||||
752 | ] | ||||
753 | |||||
754 | =back | ||||
755 | |||||
756 | |||||
757 | =head2 canonical | ||||
758 | |||||
759 | $json = $json->canonical([$enable]) | ||||
760 | |||||
761 | $enabled = $json->get_canonical | ||||
762 | |||||
763 | If C<$enable> is true (or missing), then the C<encode> method will output JSON objects | ||||
764 | by sorting their keys. This is adding a comparatively high overhead. | ||||
765 | |||||
766 | If C<$enable> is false, then the C<encode> method will output key-value | ||||
767 | pairs in the order Perl stores them (which will likely change between runs | ||||
768 | of the same script). | ||||
769 | |||||
770 | This option is useful if you want the same data structure to be encoded as | ||||
771 | the same JSON text (given the same overall settings). If it is disabled, | ||||
772 | the same hash might be encoded differently even if contains the same data, | ||||
773 | as key-value pairs have no inherent ordering in Perl. | ||||
774 | |||||
775 | This setting has no effect when decoding JSON texts. | ||||
776 | |||||
777 | =head2 allow_nonref | ||||
778 | |||||
779 | $json = $json->allow_nonref([$enable]) | ||||
780 | |||||
781 | $enabled = $json->get_allow_nonref | ||||
782 | |||||
783 | If C<$enable> is true (or missing), then the C<encode> method can convert a | ||||
784 | non-reference into its corresponding string, number or null JSON value, | ||||
785 | which is an extension to RFC4627. Likewise, C<decode> will accept those JSON | ||||
786 | values instead of croaking. | ||||
787 | |||||
788 | If C<$enable> is false, then the C<encode> method will croak if it isn't | ||||
789 | passed an arrayref or hashref, as JSON texts must either be an object | ||||
790 | or array. Likewise, C<decode> will croak if given something that is not a | ||||
791 | JSON object or array. | ||||
792 | |||||
793 | JSON->new->allow_nonref->encode ("Hello, World!") | ||||
794 | => "Hello, World!" | ||||
795 | |||||
796 | =head2 allow_unknown | ||||
797 | |||||
798 | $json = $json->allow_unknown ([$enable]) | ||||
799 | |||||
800 | $enabled = $json->get_allow_unknown | ||||
801 | |||||
802 | If $enable is true (or missing), then "encode" will *not* throw an | ||||
803 | exception when it encounters values it cannot represent in JSON (for | ||||
804 | example, filehandles) but instead will encode a JSON "null" value. | ||||
805 | Note that blessed objects are not included here and are handled | ||||
806 | separately by c<allow_nonref>. | ||||
807 | |||||
808 | If $enable is false (the default), then "encode" will throw an | ||||
809 | exception when it encounters anything it cannot encode as JSON. | ||||
810 | |||||
811 | This option does not affect "decode" in any way, and it is | ||||
812 | recommended to leave it off unless you know your communications | ||||
813 | partner. | ||||
814 | |||||
815 | =head2 allow_blessed | ||||
816 | |||||
817 | $json = $json->allow_blessed([$enable]) | ||||
818 | |||||
819 | $enabled = $json->get_allow_blessed | ||||
820 | |||||
821 | If C<$enable> is true (or missing), then the C<encode> method will not | ||||
822 | barf when it encounters a blessed reference. Instead, the value of the | ||||
823 | B<convert_blessed> option will decide whether C<null> (C<convert_blessed> | ||||
824 | disabled or no C<TO_JSON> method found) or a representation of the | ||||
825 | object (C<convert_blessed> enabled and C<TO_JSON> method found) is being | ||||
826 | encoded. Has no effect on C<decode>. | ||||
827 | |||||
828 | If C<$enable> is false (the default), then C<encode> will throw an | ||||
829 | exception when it encounters a blessed object. | ||||
830 | |||||
831 | |||||
832 | =head2 convert_blessed | ||||
833 | |||||
834 | $json = $json->convert_blessed([$enable]) | ||||
835 | |||||
836 | $enabled = $json->get_convert_blessed | ||||
837 | |||||
838 | If C<$enable> is true (or missing), then C<encode>, upon encountering a | ||||
839 | blessed object, will check for the availability of the C<TO_JSON> method | ||||
840 | on the object's class. If found, it will be called in scalar context | ||||
841 | and the resulting scalar will be encoded instead of the object. If no | ||||
842 | C<TO_JSON> method is found, the value of C<allow_blessed> will decide what | ||||
843 | to do. | ||||
844 | |||||
845 | The C<TO_JSON> method may safely call die if it wants. If C<TO_JSON> | ||||
846 | returns other blessed objects, those will be handled in the same | ||||
847 | way. C<TO_JSON> must take care of not causing an endless recursion cycle | ||||
848 | (== crash) in this case. The name of C<TO_JSON> was chosen because other | ||||
849 | methods called by the Perl core (== not by the user of the object) are | ||||
850 | usually in upper case letters and to avoid collisions with the C<to_json> | ||||
851 | function or method. | ||||
852 | |||||
853 | This setting does not yet influence C<decode> in any way. | ||||
854 | |||||
855 | If C<$enable> is false, then the C<allow_blessed> setting will decide what | ||||
856 | to do when a blessed object is found. | ||||
857 | |||||
858 | =over | ||||
859 | |||||
860 | =item convert_blessed_universally mode | ||||
861 | |||||
862 | If use C<JSON> with C<-convert_blessed_universally>, the C<UNIVERSAL::TO_JSON> | ||||
863 | subroutine is defined as the below code: | ||||
864 | |||||
865 | *UNIVERSAL::TO_JSON = sub { | ||||
866 | my $b_obj = B::svref_2object( $_[0] ); | ||||
867 | return $b_obj->isa('B::HV') ? { %{ $_[0] } } | ||||
868 | : $b_obj->isa('B::AV') ? [ @{ $_[0] } ] | ||||
869 | : undef | ||||
870 | ; | ||||
871 | } | ||||
872 | |||||
873 | This will cause that C<encode> method converts simple blessed objects into | ||||
874 | JSON objects as non-blessed object. | ||||
875 | |||||
876 | JSON -convert_blessed_universally; | ||||
877 | $json->allow_blessed->convert_blessed->encode( $blessed_object ) | ||||
878 | |||||
879 | This feature is experimental and may be removed in the future. | ||||
880 | |||||
881 | =back | ||||
882 | |||||
883 | =head2 filter_json_object | ||||
884 | |||||
885 | $json = $json->filter_json_object([$coderef]) | ||||
886 | |||||
887 | When C<$coderef> is specified, it will be called from C<decode> each | ||||
888 | time it decodes a JSON object. The only argument passed to the coderef | ||||
889 | is a reference to the newly-created hash. If the code references returns | ||||
890 | a single scalar (which need not be a reference), this value | ||||
891 | (i.e. a copy of that scalar to avoid aliasing) is inserted into the | ||||
892 | deserialised data structure. If it returns an empty list | ||||
893 | (NOTE: I<not> C<undef>, which is a valid scalar), the original deserialised | ||||
894 | hash will be inserted. This setting can slow down decoding considerably. | ||||
895 | |||||
896 | When C<$coderef> is omitted or undefined, any existing callback will | ||||
897 | be removed and C<decode> will not change the deserialised hash in any | ||||
898 | way. | ||||
899 | |||||
900 | Example, convert all JSON objects into the integer 5: | ||||
901 | |||||
902 | my $js = JSON->new->filter_json_object (sub { 5 }); | ||||
903 | # returns [5] | ||||
904 | $js->decode ('[{}]'); # the given subroutine takes a hash reference. | ||||
905 | # throw an exception because allow_nonref is not enabled | ||||
906 | # so a lone 5 is not allowed. | ||||
907 | $js->decode ('{"a":1, "b":2}'); | ||||
908 | |||||
909 | |||||
910 | =head2 filter_json_single_key_object | ||||
911 | |||||
912 | $json = $json->filter_json_single_key_object($key [=> $coderef]) | ||||
913 | |||||
914 | Works remotely similar to C<filter_json_object>, but is only called for | ||||
915 | JSON objects having a single key named C<$key>. | ||||
916 | |||||
917 | This C<$coderef> is called before the one specified via | ||||
918 | C<filter_json_object>, if any. It gets passed the single value in the JSON | ||||
919 | object. If it returns a single value, it will be inserted into the data | ||||
920 | structure. If it returns nothing (not even C<undef> but the empty list), | ||||
921 | the callback from C<filter_json_object> will be called next, as if no | ||||
922 | single-key callback were specified. | ||||
923 | |||||
924 | If C<$coderef> is omitted or undefined, the corresponding callback will be | ||||
925 | disabled. There can only ever be one callback for a given key. | ||||
926 | |||||
927 | As this callback gets called less often then the C<filter_json_object> | ||||
928 | one, decoding speed will not usually suffer as much. Therefore, single-key | ||||
929 | objects make excellent targets to serialise Perl objects into, especially | ||||
930 | as single-key JSON objects are as close to the type-tagged value concept | ||||
931 | as JSON gets (it's basically an ID/VALUE tuple). Of course, JSON does not | ||||
932 | support this in any way, so you need to make sure your data never looks | ||||
933 | like a serialised Perl hash. | ||||
934 | |||||
935 | Typical names for the single object key are C<__class_whatever__>, or | ||||
936 | C<$__dollars_are_rarely_used__$> or C<}ugly_brace_placement>, or even | ||||
937 | things like C<__class_md5sum(classname)__>, to reduce the risk of clashing | ||||
938 | with real hashes. | ||||
939 | |||||
940 | Example, decode JSON objects of the form C<< { "__widget__" => <id> } >> | ||||
941 | into the corresponding C<< $WIDGET{<id>} >> object: | ||||
942 | |||||
943 | # return whatever is in $WIDGET{5}: | ||||
944 | JSON | ||||
945 | ->new | ||||
946 | ->filter_json_single_key_object (__widget__ => sub { | ||||
947 | $WIDGET{ $_[0] } | ||||
948 | }) | ||||
949 | ->decode ('{"__widget__": 5') | ||||
950 | |||||
951 | # this can be used with a TO_JSON method in some "widget" class | ||||
952 | # for serialisation to json: | ||||
953 | sub WidgetBase::TO_JSON { | ||||
954 | my ($self) = @_; | ||||
955 | |||||
956 | unless ($self->{id}) { | ||||
957 | $self->{id} = ..get..some..id..; | ||||
958 | $WIDGET{$self->{id}} = $self; | ||||
959 | } | ||||
960 | |||||
961 | { __widget__ => $self->{id} } | ||||
962 | } | ||||
963 | |||||
964 | |||||
965 | =head2 shrink | ||||
966 | |||||
967 | $json = $json->shrink([$enable]) | ||||
968 | |||||
969 | $enabled = $json->get_shrink | ||||
970 | |||||
971 | With JSON::XS, this flag resizes strings generated by either | ||||
972 | C<encode> or C<decode> to their minimum size possible. This can save | ||||
973 | memory when your JSON texts are either very very long or you have many | ||||
974 | short strings. It will also try to downgrade any strings to octet-form | ||||
975 | if possible: perl stores strings internally either in an encoding called | ||||
976 | UTF-X or in octet-form. The latter cannot store everything but uses less | ||||
977 | space in general (and some buggy Perl or C code might even rely on that | ||||
978 | internal representation being used). | ||||
979 | |||||
980 | With JSON::PP, it is noop about resizing strings but tries | ||||
981 | C<utf8::downgrade> to the returned string by C<encode>. See to L<utf8>. | ||||
982 | |||||
983 | See to L<JSON::XS/OBJECT-ORIENTED INTERFACE> and L<JSON::PP/METHODS>. | ||||
984 | |||||
985 | =head2 max_depth | ||||
986 | |||||
987 | $json = $json->max_depth([$maximum_nesting_depth]) | ||||
988 | |||||
989 | $max_depth = $json->get_max_depth | ||||
990 | |||||
991 | Sets the maximum nesting level (default C<512>) accepted while encoding | ||||
992 | or decoding. If a higher nesting level is detected in JSON text or a Perl | ||||
993 | data structure, then the encoder and decoder will stop and croak at that | ||||
994 | point. | ||||
995 | |||||
996 | Nesting level is defined by number of hash- or arrayrefs that the encoder | ||||
997 | needs to traverse to reach a given point or the number of C<{> or C<[> | ||||
998 | characters without their matching closing parenthesis crossed to reach a | ||||
999 | given character in a string. | ||||
1000 | |||||
1001 | If no argument is given, the highest possible setting will be used, which | ||||
1002 | is rarely useful. | ||||
1003 | |||||
1004 | Note that nesting is implemented by recursion in C. The default value has | ||||
1005 | been chosen to be as large as typical operating systems allow without | ||||
1006 | crashing. (JSON::XS) | ||||
1007 | |||||
1008 | With JSON::PP as the backend, when a large value (100 or more) was set and | ||||
1009 | it de/encodes a deep nested object/text, it may raise a warning | ||||
1010 | 'Deep recursion on subroutine' at the perl runtime phase. | ||||
1011 | |||||
1012 | See L<JSON::XS/SECURITY CONSIDERATIONS> for more info on why this is useful. | ||||
1013 | |||||
1014 | =head2 max_size | ||||
1015 | |||||
1016 | $json = $json->max_size([$maximum_string_size]) | ||||
1017 | |||||
1018 | $max_size = $json->get_max_size | ||||
1019 | |||||
1020 | Set the maximum length a JSON text may have (in bytes) where decoding is | ||||
1021 | being attempted. The default is C<0>, meaning no limit. When C<decode> | ||||
1022 | is called on a string that is longer then this many bytes, it will not | ||||
1023 | attempt to decode the string but throw an exception. This setting has no | ||||
1024 | effect on C<encode> (yet). | ||||
1025 | |||||
1026 | If no argument is given, the limit check will be deactivated (same as when | ||||
1027 | C<0> is specified). | ||||
1028 | |||||
1029 | See L<JSON::XS/SECURITY CONSIDERATIONS>, below, for more info on why this is useful. | ||||
1030 | |||||
1031 | =head2 encode | ||||
1032 | |||||
1033 | $json_text = $json->encode($perl_scalar) | ||||
1034 | |||||
1035 | Converts the given Perl data structure (a simple scalar or a reference | ||||
1036 | to a hash or array) to its JSON representation. Simple scalars will be | ||||
1037 | converted into JSON string or number sequences, while references to arrays | ||||
1038 | become JSON arrays and references to hashes become JSON objects. Undefined | ||||
1039 | Perl values (e.g. C<undef>) become JSON C<null> values. | ||||
1040 | References to the integers C<0> and C<1> are converted into C<true> and C<false>. | ||||
1041 | |||||
1042 | =head2 decode | ||||
1043 | |||||
1044 | $perl_scalar = $json->decode($json_text) | ||||
1045 | |||||
1046 | The opposite of C<encode>: expects a JSON text and tries to parse it, | ||||
1047 | returning the resulting simple scalar or reference. Croaks on error. | ||||
1048 | |||||
1049 | JSON numbers and strings become simple Perl scalars. JSON arrays become | ||||
1050 | Perl arrayrefs and JSON objects become Perl hashrefs. C<true> becomes | ||||
1051 | C<1> (C<JSON::true>), C<false> becomes C<0> (C<JSON::false>) and | ||||
1052 | C<null> becomes C<undef>. | ||||
1053 | |||||
1054 | =head2 decode_prefix | ||||
1055 | |||||
1056 | ($perl_scalar, $characters) = $json->decode_prefix($json_text) | ||||
1057 | |||||
1058 | This works like the C<decode> method, but instead of raising an exception | ||||
1059 | when there is trailing garbage after the first JSON object, it will | ||||
1060 | silently stop parsing there and return the number of characters consumed | ||||
1061 | so far. | ||||
1062 | |||||
1063 | JSON->new->decode_prefix ("[1] the tail") | ||||
1064 | => ([], 3) | ||||
1065 | |||||
1066 | See to L<JSON::XS/OBJECT-ORIENTED INTERFACE> | ||||
1067 | |||||
1068 | =head2 property | ||||
1069 | |||||
1070 | $boolean = $json->property($property_name) | ||||
1071 | |||||
1072 | Returns a boolean value about above some properties. | ||||
1073 | |||||
1074 | The available properties are C<ascii>, C<latin1>, C<utf8>, | ||||
1075 | C<indent>,C<space_before>, C<space_after>, C<relaxed>, C<canonical>, | ||||
1076 | C<allow_nonref>, C<allow_unknown>, C<allow_blessed>, C<convert_blessed>, | ||||
1077 | C<shrink>, C<max_depth> and C<max_size>. | ||||
1078 | |||||
1079 | $boolean = $json->property('utf8'); | ||||
1080 | => 0 | ||||
1081 | $json->utf8; | ||||
1082 | $boolean = $json->property('utf8'); | ||||
1083 | => 1 | ||||
1084 | |||||
1085 | Sets the property with a given boolean value. | ||||
1086 | |||||
1087 | $json = $json->property($property_name => $boolean); | ||||
1088 | |||||
1089 | With no argument, it returns all the above properties as a hash reference. | ||||
1090 | |||||
1091 | $flag_hashref = $json->property(); | ||||
1092 | |||||
1093 | =head1 INCREMENTAL PARSING | ||||
1094 | |||||
1095 | Most of this section are copied and modified from L<JSON::XS/INCREMENTAL PARSING>. | ||||
1096 | |||||
1097 | In some cases, there is the need for incremental parsing of JSON texts. | ||||
1098 | This module does allow you to parse a JSON stream incrementally. | ||||
1099 | It does so by accumulating text until it has a full JSON object, which | ||||
1100 | it then can decode. This process is similar to using C<decode_prefix> | ||||
1101 | to see if a full JSON object is available, but is much more efficient | ||||
1102 | (and can be implemented with a minimum of method calls). | ||||
1103 | |||||
1104 | The backend module will only attempt to parse the JSON text once it is sure it | ||||
1105 | has enough text to get a decisive result, using a very simple but | ||||
1106 | truly incremental parser. This means that it sometimes won't stop as | ||||
1107 | early as the full parser, for example, it doesn't detect parenthesis | ||||
1108 | mismatches. The only thing it guarantees is that it starts decoding as | ||||
1109 | soon as a syntactically valid JSON text has been seen. This means you need | ||||
1110 | to set resource limits (e.g. C<max_size>) to ensure the parser will stop | ||||
1111 | parsing in the presence if syntax errors. | ||||
1112 | |||||
1113 | The following methods implement this incremental parser. | ||||
1114 | |||||
1115 | =head2 incr_parse | ||||
1116 | |||||
1117 | $json->incr_parse( [$string] ) # void context | ||||
1118 | |||||
1119 | $obj_or_undef = $json->incr_parse( [$string] ) # scalar context | ||||
1120 | |||||
1121 | @obj_or_empty = $json->incr_parse( [$string] ) # list context | ||||
1122 | |||||
1123 | This is the central parsing function. It can both append new text and | ||||
1124 | extract objects from the stream accumulated so far (both of these | ||||
1125 | functions are optional). | ||||
1126 | |||||
1127 | If C<$string> is given, then this string is appended to the already | ||||
1128 | existing JSON fragment stored in the C<$json> object. | ||||
1129 | |||||
1130 | After that, if the function is called in void context, it will simply | ||||
1131 | return without doing anything further. This can be used to add more text | ||||
1132 | in as many chunks as you want. | ||||
1133 | |||||
1134 | If the method is called in scalar context, then it will try to extract | ||||
1135 | exactly I<one> JSON object. If that is successful, it will return this | ||||
1136 | object, otherwise it will return C<undef>. If there is a parse error, | ||||
1137 | this method will croak just as C<decode> would do (one can then use | ||||
1138 | C<incr_skip> to skip the erroneous part). This is the most common way of | ||||
1139 | using the method. | ||||
1140 | |||||
1141 | And finally, in list context, it will try to extract as many objects | ||||
1142 | from the stream as it can find and return them, or the empty list | ||||
1143 | otherwise. For this to work, there must be no separators between the JSON | ||||
1144 | objects or arrays, instead they must be concatenated back-to-back. If | ||||
1145 | an error occurs, an exception will be raised as in the scalar context | ||||
1146 | case. Note that in this case, any previously-parsed JSON texts will be | ||||
1147 | lost. | ||||
1148 | |||||
1149 | Example: Parse some JSON arrays/objects in a given string and return them. | ||||
1150 | |||||
1151 | my @objs = JSON->new->incr_parse ("[5][7][1,2]"); | ||||
1152 | |||||
1153 | =head2 incr_text | ||||
1154 | |||||
1155 | $lvalue_string = $json->incr_text | ||||
1156 | |||||
1157 | This method returns the currently stored JSON fragment as an lvalue, that | ||||
1158 | is, you can manipulate it. This I<only> works when a preceding call to | ||||
1159 | C<incr_parse> in I<scalar context> successfully returned an object. Under | ||||
1160 | all other circumstances you must not call this function (I mean it. | ||||
1161 | although in simple tests it might actually work, it I<will> fail under | ||||
1162 | real world conditions). As a special exception, you can also call this | ||||
1163 | method before having parsed anything. | ||||
1164 | |||||
1165 | This function is useful in two cases: a) finding the trailing text after a | ||||
1166 | JSON object or b) parsing multiple JSON objects separated by non-JSON text | ||||
1167 | (such as commas). | ||||
1168 | |||||
1169 | $json->incr_text =~ s/\s*,\s*//; | ||||
1170 | |||||
1171 | In Perl 5.005, C<lvalue> attribute is not available. | ||||
1172 | You must write codes like the below: | ||||
1173 | |||||
1174 | $string = $json->incr_text; | ||||
1175 | $string =~ s/\s*,\s*//; | ||||
1176 | $json->incr_text( $string ); | ||||
1177 | |||||
1178 | =head2 incr_skip | ||||
1179 | |||||
1180 | $json->incr_skip | ||||
1181 | |||||
1182 | This will reset the state of the incremental parser and will remove the | ||||
1183 | parsed text from the input buffer. This is useful after C<incr_parse> | ||||
1184 | died, in which case the input buffer and incremental parser state is left | ||||
1185 | unchanged, to skip the text parsed so far and to reset the parse state. | ||||
1186 | |||||
1187 | =head2 incr_reset | ||||
1188 | |||||
1189 | $json->incr_reset | ||||
1190 | |||||
1191 | This completely resets the incremental parser, that is, after this call, | ||||
1192 | it will be as if the parser had never parsed anything. | ||||
1193 | |||||
1194 | This is useful if you want to repeatedly parse JSON objects and want to | ||||
1195 | ignore any trailing data, which means you have to reset the parser after | ||||
1196 | each successful decode. | ||||
1197 | |||||
1198 | See to L<JSON::XS/INCREMENTAL PARSING> for examples. | ||||
1199 | |||||
1200 | |||||
1201 | =head1 JSON::PP SUPPORT METHODS | ||||
1202 | |||||
1203 | The below methods are JSON::PP own methods, so when C<JSON> works | ||||
1204 | with JSON::PP (i.e. the created object is a JSON::PP object), available. | ||||
1205 | See to L<JSON::PP/JSON::PP OWN METHODS> in detail. | ||||
1206 | |||||
1207 | If you use C<JSON> with additional C<-support_by_pp>, some methods | ||||
1208 | are available even with JSON::XS. See to L<USE PP FEATURES EVEN THOUGH XS BACKEND>. | ||||
1209 | |||||
1210 | BEING { $ENV{PERL_JSON_BACKEND} = 'JSON::XS' } | ||||
1211 | |||||
1212 | use JSON -support_by_pp; | ||||
1213 | |||||
1214 | my $json = JSON->new; | ||||
1215 | $json->allow_nonref->escape_slash->encode("/"); | ||||
1216 | |||||
1217 | # functional interfaces too. | ||||
1218 | print to_json(["/"], {escape_slash => 1}); | ||||
1219 | print from_json('["foo"]', {utf8 => 1}); | ||||
1220 | |||||
1221 | If you do not want to all functions but C<-support_by_pp>, | ||||
1222 | use C<-no_export>. | ||||
1223 | |||||
1224 | use JSON -support_by_pp, -no_export; | ||||
1225 | # functional interfaces are not exported. | ||||
1226 | |||||
1227 | =head2 allow_singlequote | ||||
1228 | |||||
1229 | $json = $json->allow_singlequote([$enable]) | ||||
1230 | |||||
1231 | If C<$enable> is true (or missing), then C<decode> will accept | ||||
1232 | any JSON strings quoted by single quotations that are invalid JSON | ||||
1233 | format. | ||||
1234 | |||||
1235 | $json->allow_singlequote->decode({"foo":'bar'}); | ||||
1236 | $json->allow_singlequote->decode({'foo':"bar"}); | ||||
1237 | $json->allow_singlequote->decode({'foo':'bar'}); | ||||
1238 | |||||
1239 | As same as the C<relaxed> option, this option may be used to parse | ||||
1240 | application-specific files written by humans. | ||||
1241 | |||||
1242 | =head2 allow_barekey | ||||
1243 | |||||
1244 | $json = $json->allow_barekey([$enable]) | ||||
1245 | |||||
1246 | If C<$enable> is true (or missing), then C<decode> will accept | ||||
1247 | bare keys of JSON object that are invalid JSON format. | ||||
1248 | |||||
1249 | As same as the C<relaxed> option, this option may be used to parse | ||||
1250 | application-specific files written by humans. | ||||
1251 | |||||
1252 | $json->allow_barekey->decode('{foo:"bar"}'); | ||||
1253 | |||||
1254 | =head2 allow_bignum | ||||
1255 | |||||
1256 | $json = $json->allow_bignum([$enable]) | ||||
1257 | |||||
1258 | If C<$enable> is true (or missing), then C<decode> will convert | ||||
1259 | the big integer Perl cannot handle as integer into a L<Math::BigInt> | ||||
1260 | object and convert a floating number (any) into a L<Math::BigFloat>. | ||||
1261 | |||||
1262 | On the contrary, C<encode> converts C<Math::BigInt> objects and C<Math::BigFloat> | ||||
1263 | objects into JSON numbers with C<allow_blessed> enable. | ||||
1264 | |||||
1265 | $json->allow_nonref->allow_blessed->allow_bignum; | ||||
1266 | $bigfloat = $json->decode('2.000000000000000000000000001'); | ||||
1267 | print $json->encode($bigfloat); | ||||
1268 | # => 2.000000000000000000000000001 | ||||
1269 | |||||
1270 | See to L<MAPPING> about the conversion of JSON number. | ||||
1271 | |||||
1272 | =head2 loose | ||||
1273 | |||||
1274 | $json = $json->loose([$enable]) | ||||
1275 | |||||
1276 | The unescaped [\x00-\x1f\x22\x2f\x5c] strings are invalid in JSON strings | ||||
1277 | and the module doesn't allow to C<decode> to these (except for \x2f). | ||||
1278 | If C<$enable> is true (or missing), then C<decode> will accept these | ||||
1279 | unescaped strings. | ||||
1280 | |||||
1281 | $json->loose->decode(qq|["abc | ||||
1282 | def"]|); | ||||
1283 | |||||
1284 | See to L<JSON::PP/JSON::PP OWN METHODS>. | ||||
1285 | |||||
1286 | =head2 escape_slash | ||||
1287 | |||||
1288 | $json = $json->escape_slash([$enable]) | ||||
1289 | |||||
1290 | According to JSON Grammar, I<slash> (U+002F) is escaped. But by default | ||||
1291 | JSON backend modules encode strings without escaping slash. | ||||
1292 | |||||
1293 | If C<$enable> is true (or missing), then C<encode> will escape slashes. | ||||
1294 | |||||
1295 | =head2 indent_length | ||||
1296 | |||||
1297 | $json = $json->indent_length($length) | ||||
1298 | |||||
1299 | With JSON::XS, The indent space length is 3 and cannot be changed. | ||||
1300 | With JSON::PP, it sets the indent space length with the given $length. | ||||
1301 | The default is 3. The acceptable range is 0 to 15. | ||||
1302 | |||||
1303 | =head2 sort_by | ||||
1304 | |||||
1305 | $json = $json->sort_by($function_name) | ||||
1306 | $json = $json->sort_by($subroutine_ref) | ||||
1307 | |||||
1308 | If $function_name or $subroutine_ref are set, its sort routine are used. | ||||
1309 | |||||
1310 | $js = $pc->sort_by(sub { $JSON::PP::a cmp $JSON::PP::b })->encode($obj); | ||||
1311 | # is($js, q|{"a":1,"b":2,"c":3,"d":4,"e":5,"f":6,"g":7,"h":8,"i":9}|); | ||||
1312 | |||||
1313 | $js = $pc->sort_by('own_sort')->encode($obj); | ||||
1314 | # is($js, q|{"a":1,"b":2,"c":3,"d":4,"e":5,"f":6,"g":7,"h":8,"i":9}|); | ||||
1315 | |||||
1316 | sub JSON::PP::own_sort { $JSON::PP::a cmp $JSON::PP::b } | ||||
1317 | |||||
1318 | As the sorting routine runs in the JSON::PP scope, the given | ||||
1319 | subroutine name and the special variables C<$a>, C<$b> will begin | ||||
1320 | with 'JSON::PP::'. | ||||
1321 | |||||
1322 | If $integer is set, then the effect is same as C<canonical> on. | ||||
1323 | |||||
1324 | See to L<JSON::PP/JSON::PP OWN METHODS>. | ||||
1325 | |||||
1326 | =head1 MAPPING | ||||
1327 | |||||
1328 | This section is copied from JSON::XS and modified to C<JSON>. | ||||
1329 | JSON::XS and JSON::PP mapping mechanisms are almost equivalent. | ||||
1330 | |||||
1331 | See to L<JSON::XS/MAPPING>. | ||||
1332 | |||||
1333 | =head2 JSON -> PERL | ||||
1334 | |||||
1335 | =over 4 | ||||
1336 | |||||
1337 | =item object | ||||
1338 | |||||
1339 | A JSON object becomes a reference to a hash in Perl. No ordering of object | ||||
1340 | keys is preserved (JSON does not preserver object key ordering itself). | ||||
1341 | |||||
1342 | =item array | ||||
1343 | |||||
1344 | A JSON array becomes a reference to an array in Perl. | ||||
1345 | |||||
1346 | =item string | ||||
1347 | |||||
1348 | A JSON string becomes a string scalar in Perl - Unicode codepoints in JSON | ||||
1349 | are represented by the same codepoints in the Perl string, so no manual | ||||
1350 | decoding is necessary. | ||||
1351 | |||||
1352 | =item number | ||||
1353 | |||||
1354 | A JSON number becomes either an integer, numeric (floating point) or | ||||
1355 | string scalar in perl, depending on its range and any fractional parts. On | ||||
1356 | the Perl level, there is no difference between those as Perl handles all | ||||
1357 | the conversion details, but an integer may take slightly less memory and | ||||
1358 | might represent more values exactly than floating point numbers. | ||||
1359 | |||||
1360 | If the number consists of digits only, C<JSON> will try to represent | ||||
1361 | it as an integer value. If that fails, it will try to represent it as | ||||
1362 | a numeric (floating point) value if that is possible without loss of | ||||
1363 | precision. Otherwise it will preserve the number as a string value (in | ||||
1364 | which case you lose roundtripping ability, as the JSON number will be | ||||
1365 | re-encoded to a JSON string). | ||||
1366 | |||||
1367 | Numbers containing a fractional or exponential part will always be | ||||
1368 | represented as numeric (floating point) values, possibly at a loss of | ||||
1369 | precision (in which case you might lose perfect roundtripping ability, but | ||||
1370 | the JSON number will still be re-encoded as a JSON number). | ||||
1371 | |||||
1372 | Note that precision is not accuracy - binary floating point values cannot | ||||
1373 | represent most decimal fractions exactly, and when converting from and to | ||||
1374 | floating point, C<JSON> only guarantees precision up to but not including | ||||
1375 | the least significant bit. | ||||
1376 | |||||
1377 | If the backend is JSON::PP and C<allow_bignum> is enable, the big integers | ||||
1378 | and the numeric can be optionally converted into L<Math::BigInt> and | ||||
1379 | L<Math::BigFloat> objects. | ||||
1380 | |||||
1381 | =item true, false | ||||
1382 | |||||
1383 | These JSON atoms become C<JSON::true> and C<JSON::false>, | ||||
1384 | respectively. They are overloaded to act almost exactly like the numbers | ||||
1385 | C<1> and C<0>. You can check whether a scalar is a JSON boolean by using | ||||
1386 | the C<JSON::is_bool> function. | ||||
1387 | |||||
1388 | If C<JSON::true> and C<JSON::false> are used as strings or compared as strings, | ||||
1389 | they represent as C<true> and C<false> respectively. | ||||
1390 | |||||
1391 | print JSON::true . "\n"; | ||||
1392 | => true | ||||
1393 | print JSON::true + 1; | ||||
1394 | => 1 | ||||
1395 | |||||
1396 | ok(JSON::true eq 'true'); | ||||
1397 | ok(JSON::true eq '1'); | ||||
1398 | ok(JSON::true == 1); | ||||
1399 | |||||
1400 | C<JSON> will install these missing overloading features to the backend modules. | ||||
1401 | |||||
1402 | |||||
1403 | =item null | ||||
1404 | |||||
1405 | A JSON null atom becomes C<undef> in Perl. | ||||
1406 | |||||
1407 | C<JSON::null> returns C<undef>. | ||||
1408 | |||||
1409 | =back | ||||
1410 | |||||
1411 | |||||
1412 | =head2 PERL -> JSON | ||||
1413 | |||||
1414 | The mapping from Perl to JSON is slightly more difficult, as Perl is a | ||||
1415 | truly typeless language, so we can only guess which JSON type is meant by | ||||
1416 | a Perl value. | ||||
1417 | |||||
1418 | =over 4 | ||||
1419 | |||||
1420 | =item hash references | ||||
1421 | |||||
1422 | Perl hash references become JSON objects. As there is no inherent ordering | ||||
1423 | in hash keys (or JSON objects), they will usually be encoded in a | ||||
1424 | pseudo-random order that can change between runs of the same program but | ||||
1425 | stays generally the same within a single run of a program. C<JSON> | ||||
1426 | optionally sort the hash keys (determined by the I<canonical> flag), so | ||||
1427 | the same data structure will serialise to the same JSON text (given same | ||||
1428 | settings and version of JSON::XS), but this incurs a runtime overhead | ||||
1429 | and is only rarely useful, e.g. when you want to compare some JSON text | ||||
1430 | against another for equality. | ||||
1431 | |||||
1432 | In future, the ordered object feature will be added to JSON::PP using C<tie> mechanism. | ||||
1433 | |||||
1434 | |||||
1435 | =item array references | ||||
1436 | |||||
1437 | Perl array references become JSON arrays. | ||||
1438 | |||||
1439 | =item other references | ||||
1440 | |||||
1441 | Other unblessed references are generally not allowed and will cause an | ||||
1442 | exception to be thrown, except for references to the integers C<0> and | ||||
1443 | C<1>, which get turned into C<false> and C<true> atoms in JSON. You can | ||||
1444 | also use C<JSON::false> and C<JSON::true> to improve readability. | ||||
1445 | |||||
1446 | to_json [\0,JSON::true] # yields [false,true] | ||||
1447 | |||||
1448 | =item JSON::true, JSON::false, JSON::null | ||||
1449 | |||||
1450 | These special values become JSON true and JSON false values, | ||||
1451 | respectively. You can also use C<\1> and C<\0> directly if you want. | ||||
1452 | |||||
1453 | JSON::null returns C<undef>. | ||||
1454 | |||||
1455 | =item blessed objects | ||||
1456 | |||||
1457 | Blessed objects are not directly representable in JSON. See the | ||||
1458 | C<allow_blessed> and C<convert_blessed> methods on various options on | ||||
1459 | how to deal with this: basically, you can choose between throwing an | ||||
1460 | exception, encoding the reference as if it weren't blessed, or provide | ||||
1461 | your own serialiser method. | ||||
1462 | |||||
1463 | With C<convert_blessed_universally> mode, C<encode> converts blessed | ||||
1464 | hash references or blessed array references (contains other blessed references) | ||||
1465 | into JSON members and arrays. | ||||
1466 | |||||
1467 | use JSON -convert_blessed_universally; | ||||
1468 | JSON->new->allow_blessed->convert_blessed->encode( $blessed_object ); | ||||
1469 | |||||
1470 | See to L<convert_blessed>. | ||||
1471 | |||||
1472 | =item simple scalars | ||||
1473 | |||||
1474 | Simple Perl scalars (any scalar that is not a reference) are the most | ||||
1475 | difficult objects to encode: JSON::XS and JSON::PP will encode undefined scalars as | ||||
1476 | JSON C<null> values, scalars that have last been used in a string context | ||||
1477 | before encoding as JSON strings, and anything else as number value: | ||||
1478 | |||||
1479 | # dump as number | ||||
1480 | encode_json [2] # yields [2] | ||||
1481 | encode_json [-3.0e17] # yields [-3e+17] | ||||
1482 | my $value = 5; encode_json [$value] # yields [5] | ||||
1483 | |||||
1484 | # used as string, so dump as string | ||||
1485 | print $value; | ||||
1486 | encode_json [$value] # yields ["5"] | ||||
1487 | |||||
1488 | # undef becomes null | ||||
1489 | encode_json [undef] # yields [null] | ||||
1490 | |||||
1491 | You can force the type to be a string by stringifying it: | ||||
1492 | |||||
1493 | my $x = 3.1; # some variable containing a number | ||||
1494 | "$x"; # stringified | ||||
1495 | $x .= ""; # another, more awkward way to stringify | ||||
1496 | print $x; # perl does it for you, too, quite often | ||||
1497 | |||||
1498 | You can force the type to be a number by numifying it: | ||||
1499 | |||||
1500 | my $x = "3"; # some variable containing a string | ||||
1501 | $x += 0; # numify it, ensuring it will be dumped as a number | ||||
1502 | $x *= 1; # same thing, the choice is yours. | ||||
1503 | |||||
1504 | You can not currently force the type in other, less obscure, ways. | ||||
1505 | |||||
1506 | Note that numerical precision has the same meaning as under Perl (so | ||||
1507 | binary to decimal conversion follows the same rules as in Perl, which | ||||
1508 | can differ to other languages). Also, your perl interpreter might expose | ||||
1509 | extensions to the floating point numbers of your platform, such as | ||||
1510 | infinities or NaN's - these cannot be represented in JSON, and it is an | ||||
1511 | error to pass those in. | ||||
1512 | |||||
1513 | =item Big Number | ||||
1514 | |||||
1515 | If the backend is JSON::PP and C<allow_bignum> is enable, | ||||
1516 | C<encode> converts C<Math::BigInt> objects and C<Math::BigFloat> | ||||
1517 | objects into JSON numbers. | ||||
1518 | |||||
1519 | |||||
1520 | =back | ||||
1521 | |||||
1522 | =head1 JSON and ECMAscript | ||||
1523 | |||||
1524 | See to L<JSON::XS/JSON and ECMAscript>. | ||||
1525 | |||||
1526 | =head1 JSON and YAML | ||||
1527 | |||||
1528 | JSON is not a subset of YAML. | ||||
1529 | See to L<JSON::XS/JSON and YAML>. | ||||
1530 | |||||
1531 | |||||
1532 | =head1 BACKEND MODULE DECISION | ||||
1533 | |||||
1534 | When you use C<JSON>, C<JSON> tries to C<use> JSON::XS. If this call failed, it will | ||||
1535 | C<uses> JSON::PP. The required JSON::XS version is I<2.2> or later. | ||||
1536 | |||||
1537 | The C<JSON> constructor method returns an object inherited from the backend module, | ||||
1538 | and JSON::XS object is a blessed scalar reference while JSON::PP is a blessed hash | ||||
1539 | reference. | ||||
1540 | |||||
1541 | So, your program should not depend on the backend module, especially | ||||
1542 | returned objects should not be modified. | ||||
1543 | |||||
1544 | my $json = JSON->new; # XS or PP? | ||||
1545 | $json->{stash} = 'this is xs object'; # this code may raise an error! | ||||
1546 | |||||
1547 | To check the backend module, there are some methods - C<backend>, C<is_pp> and C<is_xs>. | ||||
1548 | |||||
1549 | JSON->backend; # 'JSON::XS' or 'JSON::PP' | ||||
1550 | |||||
1551 | JSON->backend->is_pp: # 0 or 1 | ||||
1552 | |||||
1553 | JSON->backend->is_xs: # 1 or 0 | ||||
1554 | |||||
1555 | $json->is_xs; # 1 or 0 | ||||
1556 | |||||
1557 | $json->is_pp; # 0 or 1 | ||||
1558 | |||||
1559 | |||||
1560 | If you set an environment variable C<PERL_JSON_BACKEND>, the calling action will be changed. | ||||
1561 | |||||
1562 | =over | ||||
1563 | |||||
1564 | =item PERL_JSON_BACKEND = 0 or PERL_JSON_BACKEND = 'JSON::PP' | ||||
1565 | |||||
1566 | Always use JSON::PP | ||||
1567 | |||||
1568 | =item PERL_JSON_BACKEND == 1 or PERL_JSON_BACKEND = 'JSON::XS,JSON::PP' | ||||
1569 | |||||
1570 | (The default) Use compiled JSON::XS if it is properly compiled & installed, | ||||
1571 | otherwise use JSON::PP. | ||||
1572 | |||||
1573 | =item PERL_JSON_BACKEND == 2 or PERL_JSON_BACKEND = 'JSON::XS' | ||||
1574 | |||||
1575 | Always use compiled JSON::XS, die if it isn't properly compiled & installed. | ||||
1576 | |||||
1577 | =item PERL_JSON_BACKEND = 'JSON::backportPP' | ||||
1578 | |||||
1579 | Always use JSON::backportPP. | ||||
1580 | JSON::backportPP is JSON::PP back port module. | ||||
1581 | C<JSON> includes JSON::backportPP instead of JSON::PP. | ||||
1582 | |||||
1583 | =back | ||||
1584 | |||||
1585 | These ideas come from L<DBI::PurePerl> mechanism. | ||||
1586 | |||||
1587 | example: | ||||
1588 | |||||
1589 | BEGIN { $ENV{PERL_JSON_BACKEND} = 'JSON::PP' } | ||||
1590 | use JSON; # always uses JSON::PP | ||||
1591 | |||||
1592 | In future, it may be able to specify another module. | ||||
1593 | |||||
1594 | =head1 USE PP FEATURES EVEN THOUGH XS BACKEND | ||||
1595 | |||||
1596 | Many methods are available with either JSON::XS or JSON::PP and | ||||
1597 | when the backend module is JSON::XS, if any JSON::PP specific (i.e. JSON::XS unsupported) | ||||
1598 | method is called, it will C<warn> and be noop. | ||||
1599 | |||||
1600 | But If you C<use> C<JSON> passing the optional string C<-support_by_pp>, | ||||
1601 | it makes a part of those unsupported methods available. | ||||
1602 | This feature is achieved by using JSON::PP in C<de/encode>. | ||||
1603 | |||||
1604 | BEGIN { $ENV{PERL_JSON_BACKEND} = 2 } # with JSON::XS | ||||
1605 | use JSON -support_by_pp; | ||||
1606 | my $json = JSON->new; | ||||
1607 | $json->allow_nonref->escape_slash->encode("/"); | ||||
1608 | |||||
1609 | At this time, the returned object is a C<JSON::Backend::XS::Supportable> | ||||
1610 | object (re-blessed XS object), and by checking JSON::XS unsupported flags | ||||
1611 | in de/encoding, can support some unsupported methods - C<loose>, C<allow_bignum>, | ||||
1612 | C<allow_barekey>, C<allow_singlequote>, C<escape_slash> and C<indent_length>. | ||||
1613 | |||||
1614 | When any unsupported methods are not enable, C<XS de/encode> will be | ||||
1615 | used as is. The switch is achieved by changing the symbolic tables. | ||||
1616 | |||||
1617 | C<-support_by_pp> is effective only when the backend module is JSON::XS | ||||
1618 | and it makes the de/encoding speed down a bit. | ||||
1619 | |||||
1620 | See to L<JSON::PP SUPPORT METHODS>. | ||||
1621 | |||||
1622 | =head1 INCOMPATIBLE CHANGES TO OLD VERSION | ||||
1623 | |||||
1624 | There are big incompatibility between new version (2.00) and old (1.xx). | ||||
1625 | If you use old C<JSON> 1.xx in your code, please check it. | ||||
1626 | |||||
1627 | See to L<Transition ways from 1.xx to 2.xx.> | ||||
1628 | |||||
1629 | =over | ||||
1630 | |||||
1631 | =item jsonToObj and objToJson are obsoleted. | ||||
1632 | |||||
1633 | Non Perl-style name C<jsonToObj> and C<objToJson> are obsoleted | ||||
1634 | (but not yet deleted from the source). | ||||
1635 | If you use these functions in your code, please replace them | ||||
1636 | with C<from_json> and C<to_json>. | ||||
1637 | |||||
1638 | |||||
1639 | =item Global variables are no longer available. | ||||
1640 | |||||
1641 | C<JSON> class variables - C<$JSON::AUTOCONVERT>, C<$JSON::BareKey>, etc... | ||||
1642 | - are not available any longer. | ||||
1643 | Instead, various features can be used through object methods. | ||||
1644 | |||||
1645 | |||||
1646 | =item Package JSON::Converter and JSON::Parser are deleted. | ||||
1647 | |||||
1648 | Now C<JSON> bundles with JSON::PP which can handle JSON more properly than them. | ||||
1649 | |||||
1650 | =item Package JSON::NotString is deleted. | ||||
1651 | |||||
1652 | There was C<JSON::NotString> class which represents JSON value C<true>, C<false>, C<null> | ||||
1653 | and numbers. It was deleted and replaced by C<JSON::Boolean>. | ||||
1654 | |||||
1655 | C<JSON::Boolean> represents C<true> and C<false>. | ||||
1656 | |||||
1657 | C<JSON::Boolean> does not represent C<null>. | ||||
1658 | |||||
1659 | C<JSON::null> returns C<undef>. | ||||
1660 | |||||
1661 | C<JSON> makes L<JSON::XS::Boolean> and L<JSON::PP::Boolean> is-a relation | ||||
1662 | to L<JSON::Boolean>. | ||||
1663 | |||||
1664 | =item function JSON::Number is obsoleted. | ||||
1665 | |||||
1666 | C<JSON::Number> is now needless because JSON::XS and JSON::PP have | ||||
1667 | round-trip integrity. | ||||
1668 | |||||
1669 | =item JSONRPC modules are deleted. | ||||
1670 | |||||
1671 | Perl implementation of JSON-RPC protocol - C<JSONRPC >, C<JSONRPC::Transport::HTTP> | ||||
1672 | and C<Apache::JSONRPC > are deleted in this distribution. | ||||
1673 | Instead of them, there is L<JSON::RPC> which supports JSON-RPC protocol version 1.1. | ||||
1674 | |||||
1675 | =back | ||||
1676 | |||||
1677 | =head2 Transition ways from 1.xx to 2.xx. | ||||
1678 | |||||
1679 | You should set C<suport_by_pp> mode firstly, because | ||||
1680 | it is always successful for the below codes even with JSON::XS. | ||||
1681 | |||||
1682 | use JSON -support_by_pp; | ||||
1683 | |||||
1684 | =over | ||||
1685 | |||||
1686 | =item Exported jsonToObj (simple) | ||||
1687 | |||||
1688 | from_json($json_text); | ||||
1689 | |||||
1690 | =item Exported objToJson (simple) | ||||
1691 | |||||
1692 | to_json($perl_scalar); | ||||
1693 | |||||
1694 | =item Exported jsonToObj (advanced) | ||||
1695 | |||||
1696 | $flags = {allow_barekey => 1, allow_singlequote => 1}; | ||||
1697 | from_json($json_text, $flags); | ||||
1698 | |||||
1699 | equivalent to: | ||||
1700 | |||||
1701 | $JSON::BareKey = 1; | ||||
1702 | $JSON::QuotApos = 1; | ||||
1703 | jsonToObj($json_text); | ||||
1704 | |||||
1705 | =item Exported objToJson (advanced) | ||||
1706 | |||||
1707 | $flags = {allow_blessed => 1, allow_barekey => 1}; | ||||
1708 | to_json($perl_scalar, $flags); | ||||
1709 | |||||
1710 | equivalent to: | ||||
1711 | |||||
1712 | $JSON::BareKey = 1; | ||||
1713 | objToJson($perl_scalar); | ||||
1714 | |||||
1715 | =item jsonToObj as object method | ||||
1716 | |||||
1717 | $json->decode($json_text); | ||||
1718 | |||||
1719 | =item objToJson as object method | ||||
1720 | |||||
1721 | $json->encode($perl_scalar); | ||||
1722 | |||||
1723 | =item new method with parameters | ||||
1724 | |||||
1725 | The C<new> method in 2.x takes any parameters no longer. | ||||
1726 | You can set parameters instead; | ||||
1727 | |||||
1728 | $json = JSON->new->pretty; | ||||
1729 | |||||
1730 | =item $JSON::Pretty, $JSON::Indent, $JSON::Delimiter | ||||
1731 | |||||
1732 | If C<indent> is enable, that means C<$JSON::Pretty> flag set. And | ||||
1733 | C<$JSON::Delimiter> was substituted by C<space_before> and C<space_after>. | ||||
1734 | In conclusion: | ||||
1735 | |||||
1736 | $json->indent->space_before->space_after; | ||||
1737 | |||||
1738 | Equivalent to: | ||||
1739 | |||||
1740 | $json->pretty; | ||||
1741 | |||||
1742 | To change indent length, use C<indent_length>. | ||||
1743 | |||||
1744 | (Only with JSON::PP, if C<-support_by_pp> is not used.) | ||||
1745 | |||||
1746 | $json->pretty->indent_length(2)->encode($perl_scalar); | ||||
1747 | |||||
1748 | =item $JSON::BareKey | ||||
1749 | |||||
1750 | (Only with JSON::PP, if C<-support_by_pp> is not used.) | ||||
1751 | |||||
1752 | $json->allow_barekey->decode($json_text) | ||||
1753 | |||||
1754 | =item $JSON::ConvBlessed | ||||
1755 | |||||
1756 | use C<-convert_blessed_universally>. See to L<convert_blessed>. | ||||
1757 | |||||
1758 | =item $JSON::QuotApos | ||||
1759 | |||||
1760 | (Only with JSON::PP, if C<-support_by_pp> is not used.) | ||||
1761 | |||||
1762 | $json->allow_singlequote->decode($json_text) | ||||
1763 | |||||
1764 | =item $JSON::SingleQuote | ||||
1765 | |||||
1766 | Disable. C<JSON> does not make such a invalid JSON string any longer. | ||||
1767 | |||||
1768 | =item $JSON::KeySort | ||||
1769 | |||||
1770 | $json->canonical->encode($perl_scalar) | ||||
1771 | |||||
1772 | This is the ascii sort. | ||||
1773 | |||||
1774 | If you want to use with your own sort routine, check the C<sort_by> method. | ||||
1775 | |||||
1776 | (Only with JSON::PP, even if C<-support_by_pp> is used currently.) | ||||
1777 | |||||
1778 | $json->sort_by($sort_routine_ref)->encode($perl_scalar) | ||||
1779 | |||||
1780 | $json->sort_by(sub { $JSON::PP::a <=> $JSON::PP::b })->encode($perl_scalar) | ||||
1781 | |||||
1782 | Can't access C<$a> and C<$b> but C<$JSON::PP::a> and C<$JSON::PP::b>. | ||||
1783 | |||||
1784 | =item $JSON::SkipInvalid | ||||
1785 | |||||
1786 | $json->allow_unknown | ||||
1787 | |||||
1788 | =item $JSON::AUTOCONVERT | ||||
1789 | |||||
1790 | Needless. C<JSON> backend modules have the round-trip integrity. | ||||
1791 | |||||
1792 | =item $JSON::UTF8 | ||||
1793 | |||||
1794 | Needless because C<JSON> (JSON::XS/JSON::PP) sets | ||||
1795 | the UTF8 flag on properly. | ||||
1796 | |||||
1797 | # With UTF8-flagged strings | ||||
1798 | |||||
1799 | $json->allow_nonref; | ||||
1800 | $str = chr(1000); # UTF8-flagged | ||||
1801 | |||||
1802 | $json_text = $json->utf8(0)->encode($str); | ||||
1803 | utf8::is_utf8($json_text); | ||||
1804 | # true | ||||
1805 | $json_text = $json->utf8(1)->encode($str); | ||||
1806 | utf8::is_utf8($json_text); | ||||
1807 | # false | ||||
1808 | |||||
1809 | $str = '"' . chr(1000) . '"'; # UTF8-flagged | ||||
1810 | |||||
1811 | $perl_scalar = $json->utf8(0)->decode($str); | ||||
1812 | utf8::is_utf8($perl_scalar); | ||||
1813 | # true | ||||
1814 | $perl_scalar = $json->utf8(1)->decode($str); | ||||
1815 | # died because of 'Wide character in subroutine' | ||||
1816 | |||||
1817 | See to L<JSON::XS/A FEW NOTES ON UNICODE AND PERL>. | ||||
1818 | |||||
1819 | =item $JSON::UnMapping | ||||
1820 | |||||
1821 | Disable. See to L<MAPPING>. | ||||
1822 | |||||
1823 | =item $JSON::SelfConvert | ||||
1824 | |||||
1825 | This option was deleted. | ||||
1826 | Instead of it, if a given blessed object has the C<TO_JSON> method, | ||||
1827 | C<TO_JSON> will be executed with C<convert_blessed>. | ||||
1828 | |||||
1829 | $json->convert_blessed->encode($blessed_hashref_or_arrayref) | ||||
1830 | # if need, call allow_blessed | ||||
1831 | |||||
1832 | Note that it was C<toJson> in old version, but now not C<toJson> but C<TO_JSON>. | ||||
1833 | |||||
1834 | =back | ||||
1835 | |||||
1836 | =head1 TODO | ||||
1837 | |||||
1838 | =over | ||||
1839 | |||||
1840 | =item example programs | ||||
1841 | |||||
1842 | =back | ||||
1843 | |||||
1844 | =head1 THREADS | ||||
1845 | |||||
1846 | No test with JSON::PP. If with JSON::XS, See to L<JSON::XS/THREADS>. | ||||
1847 | |||||
1848 | |||||
1849 | =head1 BUGS | ||||
1850 | |||||
1851 | Please report bugs relevant to C<JSON> to E<lt>makamaka[at]cpan.orgE<gt>. | ||||
1852 | |||||
1853 | |||||
1854 | =head1 SEE ALSO | ||||
1855 | |||||
1856 | Most of the document is copied and modified from JSON::XS doc. | ||||
1857 | |||||
1858 | L<JSON::XS>, L<JSON::PP> | ||||
1859 | |||||
1860 | C<RFC4627>(L<http://www.ietf.org/rfc/rfc4627.txt>) | ||||
1861 | |||||
1862 | =head1 AUTHOR | ||||
1863 | |||||
1864 | Makamaka Hannyaharamitu, E<lt>makamaka[at]cpan.orgE<gt> | ||||
1865 | |||||
1866 | JSON::XS was written by Marc Lehmann <schmorp[at]schmorp.de> | ||||
1867 | |||||
1868 | The release of this new version owes to the courtesy of Marc Lehmann. | ||||
1869 | |||||
1870 | |||||
1871 | =head1 COPYRIGHT AND LICENSE | ||||
1872 | |||||
1873 | Copyright 2005-2013 by Makamaka Hannyaharamitu | ||||
1874 | |||||
1875 | This library is free software; you can redistribute it and/or modify | ||||
1876 | it under the same terms as Perl itself. | ||||
1877 | |||||
1878 | =cut | ||||
1879 | |||||
1880 | |||||
1881 | ; |